// AnsiLayer.cpp: implementation of the CAnsiLayer class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "AnsiTerminal.h"
#include "AnsiLayer.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CAnsiLayer::CAnsiLayer(IAnsiScreen *pAnsiScreen) :
	m_ansiSequenceCol(pAnsiScreen)
{
	m_pAnsiScreen = pAnsiScreen;
	m_bInSequence = FALSE;
	//m_prevC = '\0';
	m_bFoundESC = FALSE;
}

CAnsiLayer::~CAnsiLayer()
{

}

BOOL CAnsiLayer::EatChar(char &c)
{
	if(m_bInSequence)
	{
		if( (c >= '0' && c <= '9') || (c == ';') )
		{
			m_sequenceBuf.Add(c);
		}
		else if(c == ESC)
		{
			m_sequenceBuf.RemoveAll();
			for(int n = 0; n < m_sequenceBuf.GetSize(); n++)
			{
				m_pAnsiScreen->PutC(m_sequenceBuf[n]);
			}
			m_bFoundESC = TRUE;
			m_sequenceBuf.RemoveAll();
			m_bInSequence = FALSE;
		}
		else
		{
			CString sParams(m_sequenceBuf.GetData(), m_sequenceBuf.GetSize());
			m_ansiSequenceCol.FindSequence(c)->SetParameters(sParams);
			m_sequenceBuf.RemoveAll();
			m_bInSequence = FALSE;
		}
		return TRUE;
	}

	if(m_bFoundESC)
	{
		if(c == '[')
		{
			m_bInSequence = TRUE;
			m_bFoundESC = FALSE;
			return TRUE;
		}
		else if(c == ESC)
		{
			m_pAnsiScreen->PutC(ESC);
			return TRUE;
		}
		else
		{
			m_pAnsiScreen->PutC(ESC);
			m_bFoundESC = FALSE;
		//	return FALSE;
		}
	}
	else if(c == ESC)
	{
		m_bFoundESC = TRUE;
		return TRUE;
	}
	else
	{
		//return FALSE;
	}

	m_pAnsiScreen->PutC(c);
	return TRUE;
}